package com.uco.thread;

import java.util.concurrent.*;

public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService executor = new ThreadPoolExecutor(3, 5, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());

        // Executors工具类创建固定数量的线程池
        ExecutorService executor2 = Executors.newFixedThreadPool(5);

        // runnable接口的 run 方法不能抛出异常，必须使用 try catch 或者 callable 接口的 call 方法
        Runnable mr = () -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " is running :" + i);
            }
        };

        Callable cr = () -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " is running :" + i);
            }
            return "success";
        };

        // 同一个 runable 对象，可以多次传入线程池
        executor.execute(mr);
        executor.execute(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " is running :" + i);
            }
        });
        executor.execute(mr);

        // 同一个 callable 对象，只能执行一次
        // callable+submit 可以通过返回的 Future 实现类对象 获取线程执行结果
        Future<String> ft = executor.submit(cr);
        // 该 ft 对象是submit的返回，不是自己写的匿名内部类，所以 get 方法和接口中的一样有编译时异常，所以要处理
        try {
            System.out.println(ft.get());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
